package cn.bellychang.loopqueue.arraylist.cl02fixedcapacity;

/**
 * @author: bellychang
 * @date: 2020/2/8
 */
public class ArrayList<E> {

    public static final int INIT_CAPACITY = 3;
    private E[] array;

    private int head;
    private int tail;

    public ArrayList(int capacity) {
        if (capacity <= 1) {
            capacity = INIT_CAPACITY;
        }
        this.array = (E[]) new Object[capacity];
        head = tail = 0;
    }

    public ArrayList() {
        new ArrayList(INIT_CAPACITY);
    }

    public int size;

    public int getSize() {
        return this.size;
    }

    public int getCapacity() {
        return array.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void addLast(E e) {
        if (this.size >= array.length) {
            throw new IllegalStateException("queue is full");
        }
        array[tail] = e;
        if (!isFull()) {
            tail = (tail + 1) % (array.length);
        }
        size++;
    }

    private boolean isFull() {
        return size == array.length;
    }

    public E getFront() {
        if (isEmpty()) {
            throw new IllegalStateException("queue is empty");
        }
        return array[head];
    }

    public E removeFirst() {
        if (isEmpty()) {
            throw new IllegalStateException("queue is empty");
        }
        E current = array[head];
        head = (head + 1) % (array.length);
        size--;
        return current;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        if (head > tail) {
            tail = tail + array.length;
        }
        for (int i = head; i < head + size; i++) {
            builder.append(array[i % array.length])
                    .append("->");
        }
        return builder.length() >= 2 ? builder.toString().substring(0, builder.length() - 2) : builder.toString();
    }
}
